#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=11;
typedef int LL;
typedef pair<vector<int>,int>P;
vector<int>g[maxn];
vector<int>state;
vector<int>ans;
map<vector<int>,bool>map1;
bool vis[maxn];
int has[maxn];
int main(void){
        cin.tie(0);std::ios::sync_with_stdio(false);
        ans.resize(10,-1);state.resize(10,-1);
        LL m;cin>>m;
        for(int i=1;i<=m;i++){
            LL x,y;cin>>x>>y;
            g[x].push_back(y);g[y].push_back(x);
            vis[x]=true;vis[y]=true;
        }
        if(m==0){
            LL num=0;
            for(int i=1;i<=8;i++){
                LL x;cin>>x;
                if(x==i) num++;
            }
            if(num==8) cout<<"0"<<endl;
            else cout<<"-1"<<endl;
            return 0;
        }
        for(int i=1;i<=8;i++){
            LL x;cin>>x;
            if(vis[x]) {
                state[i]=x;
                has[x]=1;
            }
            else{
                state[x]=0;
            }
        }
        for(int i=1;i<=9;i++){
            if(has[i]){
                ans[i]=i;
            }
            else if(!has[i]&&vis[i]){
                ans[i]=-1;
            }
            else{
                ans[i]=0;
            }
        }
        map1[state]=true;
        LL cnt=-1;
        queue<P>que;
        que.push({state,0});
        while(!que.empty()){
            P now=que.front();que.pop();
            if(now.first==ans){
                cnt=now.second;
                break;
            }
            vector<int>B=now.first;int step=now.second;
            for(int i=1;i<=9;i++){

                for(int j=0;j<g[i].size();j++){

                        int v=g[i][j];

                        if( B[v]!=-1 ) continue;

                        vector<int>nxt(B);

                        swap(nxt[i],nxt[v]);

                        if(map1.count(nxt)) continue;

                        map1[nxt]=true;

                        que.push({nxt,step+1});
                }

            }
        }
        cout<<cnt<<endl;
   	return 0;
}
